<template>
  <div class="loginBG">
    <div class="tab_login">
      <p @click="swichLogin">{{loginTypeText}}</p>
    </div>
    <div class="login_userName">
      <li>手机号码：</li>
      <view class="login_userName_input">
        <li style="width: 50px; flex: none;-webkit-flex: none" @click="selectCountryCode">{{countryCode}}</li>
        <input type="number" @input="userNameChange" maxlength="11"/>
      </view>
    </div>
    <div class="login_password">
      <li>{{passOrVcode}}</li>
      <view class="login_pass_input">
        <input :type="inputType" :password="showPass" @input="passChange"
               :maxlength="passLength" :value="currentValue"/>
        <li v-if="vcodeLogin" style="width: 100px; flex: none;-webkit-flex: none;color: #ff4545;text-align: right"
            @click="getSmscode">{{getVcode}}
        </li>
        <li v-else
            style="width: 50px; flex: none;-webkit-flex:none;text-align: center;vertical-align: middle;position: relative"
            @click="swichPassIcon">
          <i class="iconfont" :class="[showPass ? 'icon-biyanjing':'icon-zhengyan']"
             style="font-size: 20px"
          />
        </li>
      </view>
    </div>
    <div class="login_findPass_rigrester">
      <li class="login_left" @click="forgotPass">忘记密码？</li>
      <li class="login_right" @click="register">注册新账号</li>
    </div>

    <div :class="[isEnable?'button-state-black_normal':'button-state-disenable']"
         style="margin: 60px 20px 30px 20px;display: block" @click="login">
      登录
    </div>
    <div class="login_bottom">
      <div class="bottom_line">
        <li></li>
        <div>微信登录</div>
        <li></li>
      </div>
      <div class="weixinBox">
        <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="onGotUserInfo"></button>
        <i class="iconfont icon-weixin"></i>
      </div>
    </div>
  </div>
</template>

<script>
  import common from '@/utils/common'
  import {mapActions} from 'vuex'
  import {saveUserInfo, saveToken} from '@/utils/wechat'
  import wechat from '@/utils/wx'
  import {obtainSmsCode} from '@/net/commonapi'

  export default {
    data() {
      return {
        countryCode: '+86',
        passOrVcode: '验证码：',
        getVcode: '获取验证码',
        loginTypeText: '使用密码登录',
        inputType: 'number',
        currentValue: '',
        passLength: 6,
        vcodeLogin: true,
        showPass: false,
        isEnable: false,
        isUserOk: false,
        isPassOk: false,
        isVcodeOk: false,
        userName: '',
        password: '',
        sencond: 60,
        vcode: '',
        wechatCode: ''
      }
    },
    watch: {
      // 如果 `question` 发生改变，这个函数就会运行
      countryCode: function (newCountryCode, oldCountryCode) {
        this.handlerBtnByAccount()
      }
    },
    methods: {
      ...mapActions('cart', ['getCarts']),
      selectCountryCode() {
        this.$wx.jumper("../countrycode/main")
      },
      forgotPass() {
        this.$wx.jumper('../forgotPassword/main')
      },
      register() {
        this.$wx.jumper('../register/main')
      },
      swichLogin() {
        this.vcodeLogin = !this.vcodeLogin
        this.passOrVcode = this.vcodeLogin ? '验证码：' : '登录密码：'
        this.loginTypeText = this.vcodeLogin ? '使用密码登录' : '使用验证码登录'
        this.showPass = this.vcodeLogin ? false : true
        this.inputType = this.vcodeLogin ? 'number' : 'text'
        this.passLength = this.vcodeLogin ? 6 : 16
        this.currentValue = this.vcodeLogin ? this.vcode : this.password
        this.handlerBtn(this.currentValue)
      },
      swichPassIcon() {
        this.showPass = !this.showPass;
      },
      userNameChange(e) {
        this.userName = e.target.value
        this.handlerBtnByAccount()
      },
      handlerBtnByAccount() {
        if (this.countryCode == '+86') {
          this.isUserOk = this.userName.length == 11
        } else {
          this.isUserOk = this.userName.length >= 4 && this.userName.length <= 11
        }
        this.isEnable = this.isUserOk && (this.vcodeLogin ? this.isVcodeOk : this.isPassOk)
      },
      passChange(e) {
        this.handlerBtn(e.target.value)
      },
      handlerBtn(content) {
        if (this.vcodeLogin) {
          this.vcode = content
          this.isVcodeOk = this.vcode.length == 6
          this.isEnable = this.isUserOk && this.isVcodeOk
          this.currentValue = this.vcode
        } else {
          this.password = content
          this.isPassOk = this.password.length >= 6 && this.password.length <= 16
          this.isEnable = this.isUserOk && this.isPassOk
          this.currentValue = this.password
        }
      },
      login() {
        if (this.vcodeLogin) {
          this.loginByCode()
        } else {
          this.loginByPass()
        }
      },
      async getSmscode() {
        if (!this.isUserOk) {
          this.$wx.showLongToast('请填写手机号码')
          return
        }
        const data = await obtainSmsCode({
          phone: this.userName,
          type: '3'
        })
        if (data.successCode) {
          const self = this
          clearInterval(this.timerNum)
          this.timerNum = setInterval(function () {
            self.sencond--
            if (self.sencond <= 0) {
              self.resetTimer()
            } else {
              self.getVcode = '(' + self.sencond + ')s'
            }
          }, 1000)
          this.$wx.showLongToast('获取验证码成功')
        } else {
          this.$wx.showLongToast(data.message)
        }
      },
      async loginByCode() {
        const loginData = await this.$fly.post(this.$url.URL_USER_FASTLOGIN, {
          country_code: this.countryCode,
          phone: this.userName,
          vcode: this.vcode
        })
        if (loginData.successCode) {
          this.loginSuccess(loginData.data)
        } else {
          this.$wx.showShortToast(loginData.message)
        }
      },
      async loginByPass() {
        const loginData = await this.$fly.post(this.$url.URL_USER_LOGIN, {
          country_code: this.countryCode,
          phone: this.userName,
          passwd: this.password
        })
        if (loginData.successCode) {
          this.loginSuccess(loginData.data)
        } else {
          this.$wx.showShortToast(loginData.message)
        }
      },
      onGotUserInfo(userInfo) {
        let self = this
        if (!this.$wx.isEmpty(this.wechatCode)) {
          self.wechatLogin(userInfo, this.wechatCode)
        } else {
          wechat.login({
            timeout: 10 * 1000,
            success: (res) => {
              self.wechatLogin(userInfo, res.code)
            }
          })
        }
      },
      async wechatLogin(userInfo, code) {
        const loginData = await this.$fly.post(this.$url.URL_MINI_LOGIN, {
          code: code,
          encryptData: userInfo.target.encryptedData,
          iv: userInfo.target.iv
        })
        if (loginData.successCode) {
          if (loginData.data.is_bind) {
            this.loginSuccess(loginData.data)
          } else {
            this.$wx.jumper('../bindphone/main')
          }
        } else {
          this.$wx.showShortToast(loginData.message)
        }
      },
      async loginSuccess(loginInfo) {
        await saveUserInfo(loginInfo)
        await saveToken(loginInfo.access_token)
        this.getCarts()   //更新购物袋
        this.$root.$eventHub.$emit('requestProductInfo', '')  //更新商品详情
        this.$root.$eventHub.$emit('requestGoods', true)  //更新商品列表
        this.$root.$eventHub.$emit('requestGoods2', true)  //更新商品列表
        this.$wx.back(1)
      },
      resetTimer() {
        this.sencond = 60
        this.getVcode = '获取验证码'
        clearInterval(this.timerNum)
      }
    },
    mounted() {
      if (!this.$wx.isArrayEmpty(this.$root.$eventHub._events.countryCodeChange)) {
        this.$root.$eventHub.$off('countryCodeChange')
      }
      this.$root.$eventHub.$on('countryCodeChange', (item) => {
        this.countryCode = item.code
      })
    },
    destroyed() {
      this.$root.$eventHub.$off('countryCodeChange')
    },
    created() {
    },
    onLoad() {
      wechat.login({
        timeout: 10 * 1000,
        success: (res) => {
          console.log(res)
          this.wechatCode = res.code
        }
      })
      console.log(this.vcodeLogin, this.showPass, 'onLoad')
      this.$wx.setTitleBarTitle('登录')
    },
    onUnload() {
      this.countryCode = '+86'
      this.passOrVcode = '验证码：'
      this.getVcode = '获取验证码'
      this.loginTypeText = '使用密码登录'
      this.inputType = 'number'
      this.currentValue = ''
      this.passLength = 6
      this.vcodeLogin = true
      this.showPass = false
      this.isEnable = false
      this.isUserOk = false
      this.isPassOk = false
      this.isVcodeOk = false
      this.userName = ''
      this.password = ''
      this.sencond = 60
      this.vcode = ''
      this.wechatCode = ''
      this.resetTimer()
    }
  }
</script>

<style>
  .login_btn {
    font-size: 18px;
  }

  .tab_login {
    position: relative;
    font-family: "Arial Black";
    font-weight: bold;
    font-size: 12px;
    padding-top: 100px;
    padding-right: 20px;
    text-align: right;
  }

  .login_userName_input {
    display: flex;
    display: -webkit-flex;
  }

  .login_pass_input {
    display: flex;
    display: -webkit-flex;
  }

  .login_pass_input input {
    flex: 1;
    -webkit-flex: 1;
    display: inline-block;
    height: 40px;
  }

  .login_pass_input li {
    flex: 1;
    -webkit-flex: 1;
    display: inline-block;
    height: 40px;
    line-height: 40px;
  }

  .login_userName_input input {
    flex: 1;
    -webkit-flex: 1;
    display: inline-block;
    height: 40px;
  }

  .login_userName_input li {
    flex: 1;
    -webkit-flex: 1;
    display: inline-block;
    height: 40px;
    line-height: 40px;
  }

  .login_userName {
    margin-left: 20px;
    margin-right: 20px;
    margin-top: 10px;
    border-bottom: 1px solid black;
  }

  .login_password {
    margin-left: 20px;
    margin-right: 20px;
    margin-top: 10px;
    border-bottom: 1px solid black;
  }

  .login_findPass_rigrester {
    position: relative;
    margin-top: 10px;
    margin-left: 20px;
    margin-right: 20px;
  }

  .login_left {
    font-size: 12px;
    position: absolute;
    text-decoration: underline;
  }

  .login_right {
    font-size: 12px;
    position: absolute;
    right: 0;
  }

  .login_bottom {
    position: absolute;
    left: 0;
    width: 100%;
    bottom: 20px;
    text-align: center;
  }

  .weixinBox {
    position: relative;
  }

  .weixinBox button {
    position: absolute;
    top: 20px;
    left: 42%;
    width: 60px;
    height: 60px;
    opacity: 0;

  }

  .icon-weixin {
    font-size: 60px;
  }

  .bottom_line {
    height: 30px;
    display: flex;
    margin: 0 20px;
    position: relative;
  }

  .bottom_line li {
    height: 1px;
    background: black;
    margin-top: 15px;
    flex: 1;
    -webkit-flex: 1;
    display: inline-block;
  }

  .bottom_line div {
    width: 70px;
    display: inline-block;
    position: relative;
    font-size: 16px;
    margin: 0 10px;
  }

</style>
